package com.springstudy.utils;


import com.springstudy.anno.MyComponent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Tamako
 * @since 2025/1/6 14:19
 */
public class BaseClassScanUtils {
    private static final String RESOURCE_PATTERN = "/**/*.class";

    public static Map<String, Class<?>> scanMyComponentAnnotation(String basePackage) {
        Map<String, Class<?>> annotationMap = new HashMap<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(basePackage) + RESOURCE_PATTERN;
            Resource[] resources = resolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resolver);
            for (Resource resource : resources) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(MyComponent.class)) {
                    MyComponent annotation = clazz.getAnnotation(MyComponent.class);
                    String beanName = annotation.value();
                    if (beanName != null && !beanName.isEmpty()) {
                        annotationMap.put(beanName, clazz);
                        continue;
                    }
                    annotationMap.put(clazz.getSimpleName(), clazz);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return annotationMap;
    }

    public static void main(String[] args) {
        Map<String, Class<?>> annotationMap = scanMyComponentAnnotation("com.springstudy");
        System.out.println(annotationMap);
    }
}
